package com.xuecheng.framework.exception;


import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionCatch {
    //定义map 保存异常与对应的错误信息
    private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTIONS;
    //定义map的builder 用于创建ImmutableMap的map ImmutableMap 线程安全，一旦添加，value只读
    private static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder=ImmutableMap.builder();

    static {
//        保存非自定义异常的异常到map中
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }

    //自定义异常捕获处理
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException e){
        ResultCode resultCode = e.getResultCode();
        return new ResponseResult(resultCode);
    }
    //不可预知异常捕获处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e){
        if (EXCEPTIONS==null){
            //创建EXCEPTION
            EXCEPTIONS=builder.build();
        }
        //从EXCEPTION获取 exception的的对应的ResultCode，如果有，就说明存在非自定义异常中，自己已保存识别的异常，否则返回CommonCode 99999
        ResultCode resultCode=EXCEPTIONS.get(e.getClass());
        if(resultCode!=null){
            return new ResponseResult(resultCode);
        }else {
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }
    }


}
